import type { UserConfig, ConfigEnv } from "vite";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { NaiveUiResolver } from "unplugin-vue-components/resolvers";
import { resolve } from "path";
import autoprefixer from "autoprefixer";
import tailwindcss from "tailwindcss";
import { wrapperEnv } from "./build/utils";
import { createProxy } from "./build/vite/proxy";

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const envDir = resolve("envs");

  const env = loadEnv(mode, envDir);
  const viteEnv = wrapperEnv(env);

  const isBuild = command === "build";

  const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY } = viteEnv;

  return defineConfig({
    base: VITE_PUBLIC_PATH,
    root,
    envDir,
    server: {
      host: true,
      port: VITE_PORT,
      proxy: createProxy(VITE_PROXY),
    },
    plugins: [
      vue(),
      AutoImport({
        imports: [
          "vue",
          {
            "naive-ui": [
              "useDialog",
              "useMessage",
              "useNotification",
              "useLoadingBar",
            ],
          },
        ],
      }),
      Components({
        resolvers: [NaiveUiResolver()],
      }),
    ],
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import './src/common/styles/_variable.scss';`,
        },
      },
      postcss: {
        plugins: [
          tailwindcss(),
          autoprefixer({
            // 指定目标浏览器
            overrideBrowserslist: [
              "Android 4.1",
              "iOS 7.1",
              "Chrome > 31",
              "ff > 31",
              "ie >= 8",
            ],
            grid: true,
          }),
        ],
      },
    },
    build: {
      minify: "esbuild",
      target: "es2015",
      cssTarget: "chrome80",
      rollupOptions: {
        output: {
          entryFileNames: "assets/[name].js",
          assetFileNames: "assets/[name].[ext]",
          chunkFileNames: "assets/[name]-[hash].js",
          manualChunks: {
            "naive-ui-vendor": ["naive-ui"],
            // 将 Lodash 库的代码单独打包
            "lodash-es-vendor": ["lodash-es"],
            // vue vue-router合并打包
            vue: ["vue", "vue-router"],
          },
        },
      },
      // 提高超大静态资源警告大小
      chunkSizeWarningLimit: 2000,
    },
    esbuild: {
      //清除全局的console.log和debug
      drop: isBuild ? ["console", "debugger"] : [],
    },
    optimizeDeps: {
      esbuildOptions: {
        target: "es2020",
      },
    },
  });
};
